package com.degon.hsyl.customchatapp.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.degon.hsyl.customchatapp.R;
import com.degon.hsyl.customchatapp.model.RongYunUserInfo;
import com.degon.hsyl.customchatapp.util.HttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SendMessageActivity extends AppCompatActivity {

    private String senderId;
    private String targetId;

    private EditText inputText;
    private RelativeLayout sendBtn;
    private ImageView backBtn;

    private Handler handler;
    private RongYunUserInfo senderInfo;
    private RongYunUserInfo receiverInfo;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_message);

        initViews();

        senderId = this.getIntent().getStringExtra("senderId");
        targetId = this.getIntent().getStringExtra("targetId");

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    senderInfo = (RongYunUserInfo) msg.obj;
                } else if (msg.what == 2) {
                    receiverInfo = (RongYunUserInfo) msg.obj;
                }
            }
        };

        getSenderInfo(senderId);
        getReceiverInfo(targetId);

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputText.getText().toString().equals("")) {
                    ToastUtils.showShort("请输入一些东西");
                } else {
                    sendTextMessage(inputText.getText().toString(), targetId);
                }
            }
        });

    }

    private void sendTextMessage(String content, String targetId) {

        Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
        TextMessage textMessage = TextMessage.obtain(content);
        UserInfo userInfo = new UserInfo(senderId, senderInfo.getUserName(), Uri.parse(senderInfo.getUserPortrait()));
        textMessage.setUserInfo(userInfo);

        io.rong.imlib.model.Message message = io.rong.imlib.model.Message.obtain(targetId, conversationType, textMessage);
        RongIMClient.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(io.rong.imlib.model.Message message) {

            }

            @Override
            public void onSuccess(io.rong.imlib.model.Message message) {
                ToastUtils.showShort("发送成功");
            }

            @Override
            public void onError(io.rong.imlib.model.Message message, RongIMClient.ErrorCode errorCode) {
                ToastUtils.showShort("发送失败");
            }
        });
    }

    private void initViews() {
        inputText = findViewById(R.id.文本输入);
        backBtn = findViewById(R.id.发送消息页_返回按钮);
        sendBtn = findViewById(R.id.发送消息);

    }

    private void getSenderInfo(String id) {
        String url = "https://api-cn.ronghub.com/user/info.json";
        RequestBody body = new FormBody.Builder()
                .add("userId", id)
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.rongYunPost(url, body);
                    RongYunUserInfo model = new Gson().fromJson(response.body().string(), RongYunUserInfo.class);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = model;
                    handler.handleMessage(message);
                } catch (IOException | NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void getReceiverInfo(String id) {

        String url = "https://api-cn.ronghub.com/user/info.json";
        RequestBody body = new FormBody.Builder()
                .add("userId", id)
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.rongYunPost(url, body);
                    RongYunUserInfo model = new Gson().fromJson(response.body().string(), RongYunUserInfo.class);
                    Message message = new Message();
                    message.what = 2;
                    message.obj = model;
                    handler.handleMessage(message);
                } catch (IOException | NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}